import axios from "axios";
import {useUserStore} from "@/stores/uerStore.js";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";

const  httpInstance =axios.create(
    {
       // baseURL:'http://localhost/apiu',
         baseURL:'https://dongdong.cloud/apiu',
        // baseURL:'http://localhost:8083',
        timeout:20000,
    }
)
// 添加请求拦截器
httpInstance.interceptors.request.use(config => {
    try{
        const token = useUserStore().userInfo.token;
        if (token) {
            //这个是在yam中配置的这个名称
            config.headers['authentication'] =token
            // config.headers.Authorization = `Bearer ${token}`
            // config.headers.Authorization = token
        } else if (token && config.url != '/login') {
            window.location.href = '/login'
            return false
        }
    }catch (e){
        console.error(e)
    }

    // 在发送请求之前做些什么
    return config;
}, error=> {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
//httpInstance.interceptors.response.use(response => response.data, error=> {
httpInstance.interceptors.response.use((response) => {
    console.log("+++++++++++++++>"+response);
    let res = response.data;
    // 若生产环境用 result 代替 data，统一转为 data
    if (res.result !== undefined && res.data === undefined) {
        res.data = res.result;
        delete res.result;
    }
    return res; // 确保后续代码能读到 res.data
}, error=> {

    console.log("+++++++++++++++>"+error);
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    ElMessage({
        type:'warning',
        message: error.response.data.message,
    })
   if(error.response.status === 401){
       useUserStore().clearUserInfo()
       router.push('/login')

   }
    return Promise.reject(error);
});
export default httpInstance;